package utils

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
)

// ReadJSON 打开读取解析JSON文件
func ReadJSON(name string, js interface{}) error {
	data, err := os.ReadFile(name)
	if err == nil {
		return json.Unmarshal(data, js)
	} else {
		return err
	}
}

func ReadConfigJSON(filename string, obj interface{}) error {
	curDir, err := os.Getwd()
	fmt.Printf("curDir=%s\n", curDir)
	if err != nil {
		return err
	}
	fpath := filepath.Join(curDir, "config", filename)
	data, err := os.ReadFile(fpath)
	if err == nil {
		return json.Unmarshal(data, obj)
	} else if !os.IsNotExist(err) {
		return err
	}
	fpath = filepath.Join(filepath.Dir(curDir), "configFile", filename)
	data, err = os.ReadFile(fpath)
	if err == nil {
		return json.Unmarshal(data, obj)
	} else if runtime.GOOS == "linux" || !os.IsNotExist(err) {
		return err
	}
	fpath = filepath.Join(filepath.Dir(curDir), "services/configFile", filename)
	data, err = os.ReadFile(fpath)
	if err != nil {
		return err
	}
	return json.Unmarshal(data, obj)
}

func RunFuncName() string {
	pc := make([]uintptr, 1)
	runtime.Callers(2, pc)
	f := runtime.FuncForPC(pc[0])
	return f.Name()
}

func GetConfigPath(fname string) (fpath string, err error) {
	curDir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	fpath = filepath.Join(curDir, "config", fname)
	_, err = os.Stat(fpath)
	if err == nil {
		return fpath, nil
	} else if os.IsNotExist(err) {
		fpath = filepath.Join(filepath.Dir(curDir), "configFile", fname)
		_, err = os.Stat(fpath)
		if err == nil {
			return fpath, nil
		} else {
			return "", err
		}
	}
	return "", err
}

// 切片中查找
func FindInSet(items interface{}, value interface{}) int {
	sVal := reflect.ValueOf(items)
	for i := 0; i < sVal.Len(); i++ {
		if sVal.Index(i).Interface() == value {
			return i
		}
	}

	return -1
}
